package com.fas.core.util.datadict;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;

import com.fas.core.constant.R;
import com.fas.hehe.config.model.DictionaryData;
import com.jfinal.kit.StrKit;

/**
 * 数据字段工具类
 * 
 *
 * @Copyright: Copyright (c) 2016 FAS 
 * @anthor yixiaoping<thinker1013@163.com>
 * @since 2016年1月23日 下午10:46:30
 * @version V1.0
 */
public class DataDicKit {
	private static DataDicKit me = new DataDicKit();
	private final static String DICT_PREFIX = "$";// 标签前缀

	private DataDicKit() {
	}

	public static DataDicKit me() {
		return me;
	}

	public List<DictionaryData> getDatadicIitemsByGroupCode(String groupCode,
			Long corpid) {
		String sql = "select * from config_dictionary_data where dict_code =? and available = ? order by priority asc";
		return DictionaryData.dao.findByCache(R.CacheName.GLOBAL_DICT_DATA, groupCode, sql,
				groupCode,  R.Dict.STATUS_AVAILABLE);
	}

	public List<DataDic> getDatadicByGroupCode(String groupCode, Long cropid) {
		List<DictionaryData> recordList = getDatadicIitemsByGroupCode(groupCode, cropid);
		List<DataDic> dataList = new ArrayList<DataDic>();
		if (CollectionUtils.isNotEmpty(recordList)) {
			for (DictionaryData items : recordList) {
				DataDic dataDic = new DataDic();
				dataDic.setValue(items.getDictdataValue());
				dataDic.setName(items.getDictdataName());
				dataDic.setTranClass(items.getTranClass());
				dataList.add(dataDic);
			}
		}
		return dataList;
	}

	public List<DataDic> getDatadicByGroupTag(String groupTag) {
		return this.getDatadicByGroupTag(groupTag, null);
	}
	
	public List<DataDic> getDatadicByGroupTag(String groupTag, Long cropid) {
		String groupCode = this.getGroupCodeByTag(groupTag);
		return this.getDatadicByGroupCode(groupCode, cropid);
	}

	public String getDictItemNameByCode(String groupTag, String value) {
		return this.getDictItemNameByCode(groupTag, value, null);
	}
	public String getDictItemNameByCode(String groupTag, String value,
			Long cropid) {
		String itemName = "";
		if (StrKit.isBlank(value)) {
			return itemName;
		}

		String groupCode = this.getGroupCodeByTag(groupTag);
		List<DictionaryData> recordList = this.getDatadicIitemsByGroupCode(groupCode,
				cropid);
		for (DictionaryData sysDict : recordList) {
			if (StrKit.notNull(value) && value.equals(sysDict.getDictdataValue())) {
				itemName = sysDict.getDictdataName();
				break;
			}
		}
		return itemName;
	}

	public String getGroupCodeByTag(String groupTag) {
		String groupCode = "";
		if (StrKit.notBlank(groupTag) && groupTag.startsWith(DICT_PREFIX)) {
			groupCode = groupTag.substring(1);
		}
		return groupCode;
	}

	public String getDictPrefix() {
		return DICT_PREFIX;
	}
}
